# coding=utf-8
"""
    @project: qabot
    
    @file： team_serializers.py
    @date：2023/9/5 16:32
    @desc:
"""

from django.core import cache
from django.db.models import Q, QuerySet
from drf_yasg import openapi
from rest_framework import serializers
from common.util import common as util
from common.exception.app_exception import AppApiException

from common.mixins.api_mixin import ApiMixin
from django.utils.translation import gettext_lazy as _
from xpack.models import Config
user_cache = cache.caches['user_cache']

class ConfigSerializer(ApiMixin, serializers.ModelSerializer):
    class Meta:
        model = Config
        fields = ["platform", "id", "config", "app_id", "create_time", "update_time","is_valid","is_active"]

    def get_response_body_api(self):
        return openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=["platform", "id", "config", "app_id", "create_time", "update_time"],
            properties={
                'id': openapi.Schema(type=openapi.TYPE_STRING, title="ID", description="ID"),
                'platform': openapi.Schema(type=openapi.TYPE_STRING, title=_("Username"), description=_("Username")),
                'app_id': openapi.Schema(type=openapi.TYPE_STRING, title=_("Email"), description=_("Email")),
                'config': openapi.Schema(type=openapi.TYPE_STRING, title=_("Role"), description=_("Role"))
            }
        )
    class Status(serializers.Serializer):
        app_id = serializers.CharField(required=True)
        platform = serializers.CharField(required=False)
        status = serializers.BooleanField(required=False)
        def save(self, with_valid=True):
            if with_valid:
                self.is_valid(raise_exception=True)
            data = {
                'platform': self.data.get('platform'),
                'app_id': self.data.get('app_id'),
                'is_active': self.data.get('status')
            }
            if self.data.get('platform') is None:
                raise AppApiException(500, _('Platform type, for example: wechat'))
            info = QuerySet(Config).filter(app_id=data['app_id'], platform=data['platform']).first()
            if info:
                QuerySet(Config).filter(id=info.id).update(**data)
            else:
                QuerySet(Config).create(**data)
            return data
        def list(self, with_valid=True):
            if with_valid:
                self.is_valid(raise_exception=True)
            data = {
                'app_id': self.data.get('app_id')
            }
            list = Config.objects.values_list("platform","is_active","is_valid")
            res = {
                "dingtalk": [True, False],
                "feishu": [True, False],
                "wechat": [True, False],
                "wecom": [True, False]
            }
            for platform,is_valid,is_active in list:
                res[platform][0] = is_valid
                res[platform][1] = is_active

            return res
    class Create(serializers.Serializer):
        app_id = serializers.CharField(required=True)
        platform = serializers.CharField(required=True)
        content = serializers.CharField(required=True)
        def save(self, with_valid=True):
            if with_valid:
                self.is_valid(raise_exception=True)
            data = {
                'platform': self.data.get('platform'),
                'app_id': self.data.get('app_id'),
                'config': self.data.get('content')
            }
            info = QuerySet(Config).filter(app_id=data['app_id'], platform=data['platform']).first()
            if info:
                QuerySet(Config).filter(id=info.id).update(**data)
            else:
                QuerySet(Config).create(**data)
            return data
    class Query(ApiMixin, serializers.Serializer):
        app_id = serializers.CharField(required=True)
        platform = serializers.CharField(required=True)
        def info(self, with_valid=True):
            if with_valid:
                self.is_valid(raise_exception=True)
            platform = self.data.get('platform')
            app_id = self.data.get('app_id')
            info = QuerySet(Config).filter(platform=platform, app_id=app_id).first()
            if not info:
                return None
            return util.parse_json(info.config)
    
    class Source(ApiMixin, serializers.Serializer):
        app_id = serializers.CharField(required=False)
        platform = serializers.CharField(required=False)
        def list(self, with_valid=True):
            if with_valid:
                self.is_valid(raise_exception=True)
            list = QuerySet(Config).all()
            return ConfigSerializer(instance=list,many=True)

   
